package com.mt.mtyx.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mt.mtyx.acl.mapper.AdminRoleMapper;
import com.mt.mtyx.acl.mapper.RoleMapper;
import com.mt.mtyx.acl.service.RoleService;
import com.mt.mtyx.entity.acl.AdminRole;
import com.mt.mtyx.entity.acl.Role;
import com.mt.mtyx.entity.base.BaseEntity;
import com.mt.mtyx.vo.acl.RoleQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 角色 业务层
 * extends ServiceImpl<RoleMapper, Role>，使用mybatisPlus 的ServiceImpl，封装 RoleMapper，不再需要手动注入
 *
 * @author WMT
 * @Date 2023/6/14 20:25
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Override
    public IPage<Role> getRoleList(Page<Role> pageParam, RoleQueryVo roleQueryVo) {

        // 1.获取条件值：角色名称
        if (roleQueryVo != null) {
            String roleName = roleQueryVo.getRoleName();

            // 2.创建条件构造器对象
            LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();

            // 3.封装条件
            if (!StringUtils.isEmpty(roleName)) {
                // 相当于 role_name like #{roleName}
                queryWrapper.like(Role::getRoleName, roleName);
            }
            // 4.调用mapper方法实现条件分页查询
            return baseMapper.selectPage(pageParam, queryWrapper);
        }

        return null;
    }

    @Override
    public int insert(Role role) {
        return baseMapper.insert(role);
    }

    @Override
    public int delete(Long id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public int batchDelete(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids);
    }

    @Override
    public int update(Role role) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", role.getId());
        return baseMapper.update(role, queryWrapper);
    }

    @Override
    public int selectCountByName(String roleName) {
        return baseMapper.selectCountByName(roleName);
    }

    @Override
    public Map<String, Object> getRoleByUserId(Long adminId) {
        // 1.查询所有的角色
        List<Role> allRoles = baseMapper.selectList(null);

        // 2.拥有的角色id
        List<AdminRole> adminRoles = adminRoleMapper.selectList(
                new QueryWrapper<AdminRole>().eq("admin_id", adminId).select("role_id")
        );

        List<Long> ids = null;
        if (adminRoles != null && !adminRoles.isEmpty()) {
            ids = adminRoles.stream()
                    .map(AdminRole::getRoleId)
                    .collect(Collectors.toList());
        }

        // 3.已分配的角色
        List<Role> assignRoles = new ArrayList<>();
        for (Role role : allRoles) {
            if (ids != null && !ids.isEmpty()) {
                if (ids.contains(role.getId())) {
                    assignRoles.add(role);
                }
            }
        }

        Map<String, Object> map = new HashMap<>(2);
        map.put("assignRoles", assignRoles);
        map.put("allRolesList", allRoles);
        return map;
    }

    @Override
    public int saveAdminRole(Long adminId, List<Long> roleIds) {
        LocalDateTime now = LocalDateTime.now();
        // 1.先删除原有角色
        LambdaQueryWrapper<AdminRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdminRole::getAdminId, adminId);
        adminRoleMapper.delete(wrapper);

        // 2.保存新的角色
        List<AdminRole> list = roleIds.stream()
                .map(data -> {
                    AdminRole adminRole = new AdminRole();
                    adminRole.setAdminId(adminId);
                    adminRole.setRoleId(data);
                    adminRole.setCreateTime(now);
                    adminRole.setUpdateTime(now);
                    adminRole.setIsDeleted(BaseEntity.NOT_DELETED);
                    return adminRole;
                })
                .collect(Collectors.toList());

        return adminRoleMapper.batchSave(list);
    }
}
